package view.listeners;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JTextField;

import model.Constants;
import model.IPAddress;
import model.Octet;
import model.Subnet;
import view.components.HostComboBox;
import view.components.SubnetComboBox;
import view.dialogs.InfoDialog;
import view.views.dialogContentViews.SubnetBoxPanel;
import controller.Calculator;
import controller.Controller;

public class SubBoxListener implements ItemListener {

	private final HostComboBox hostBox;
	private final SubnetComboBox subnetBox;
	private final SubnetBoxPanel subnetBoxPanel;

	public SubBoxListener(HostComboBox hostBox, SubnetComboBox subnetBox,
			SubnetBoxPanel subnetBoxPanel) {

		this.hostBox = hostBox;
		this.subnetBox = subnetBox;
		this.subnetBoxPanel = subnetBoxPanel;
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if (e.getStateChange() == 2) {

			hostBox.getBox().setEnabled(false);
			if (!subnetBox.getBox().getSelectedItem().equals(Constants.EMPTY)) {
				Subnet sub = subnetBox.getMap().get(
						subnetBox.getBox().getSelectedItem());
				Controller.getInstance().setCurrentSubnet(sub);

					Octet[] startAddress = null;
					for (IPAddress octet : sub.getIpAddressList()) {
						if (octet.getAdditionalInfo().equals(Constants.FREEIP)) {
							startAddress = octet.getAddressBits();
							break;
						}
					}
					if (startAddress == null) {
						new InfoDialog(Constants.ERROR, Constants.NOMORESPACE);
					} else {
					int firstBit = startAddress[0].getBitValue();
					int secondBit = startAddress[1].getBitValue();
					int thirdBit = startAddress[2].getBitValue();
					int fourthBit = startAddress[3].getBitValue();

					Calculator.getInstance().modifyIpTextArea(firstBit,
							secondBit, thirdBit, fourthBit, subnetBoxPanel);
					}
				}

			} else {
				hostBox.getBox().setEnabled(true);
				Controller.getInstance().setCurrentSubnet(null);
				for (JTextField element : subnetBoxPanel.getIpText()
						.getTextList()) {
					element.setEditable(true);
					element.setText(Constants.EMPTY);
				}
				for (JTextField element : subnetBoxPanel.getIpText()
						.getDotList()) {
					element.setBackground(new Color(255, 255, 255));

				}
			}


			}


		}




